import errorCode from '@/utils/errorCode.js'
import {
	toast,
	showConfirm,
	tansParams
} from '@/utils/common.js'

let timeout = 10000

export let baseUrl = 'https://fangwu.ilyixy.com/prod-api';

const request = config => {
	let header = {}
	let getToken = uni.getStorageSync('token')
	// let getToken = 'eyJhbGciOiJIUzUxMiJ9.eyJtaW5pX2xvZ2luX3VzZXJfa2V5IjoiMTAwNGMyYTItYWM0Mi00OWIwLTk5MTAtZDk0Y2YyOTEyZjdmIn0.ZlOfz0aiJ59ljR9IOu6qOZQVkO19nJOf4BLRsoR_XencVLeJYlPPGtCEHDEKHr_Q8NF9ydEVOyJIY6oa8Sisdw'

	// 是否需要设置 token
	const isToken = (config.headers || {}).isToken === false
	config.header = config.header || {}
	if (getToken && !isToken) {
		config.header['Authorization'] = getToken
	}
	// get请求映射params参数
	if (config.params) {
		let url = config.url + '?' + tansParams(config.params)
		url = url.slice(0, -1)
		config.url = url
	}
	let myAgent = {
		'Fw-Agent': 'mini/1.0.0'
	}
	header = {
		...header,
		...myAgent,
		...config.header,
	}
	return new Promise((resolve, reject) => {
		uni.request({
			method: config.method || 'get',
			timeout: config.timeout || timeout,
			url: baseUrl + '/mini' + config.url,
			data: config.data,
			header: header,
			dataType: 'json'
		}).then(response => {
			let res = response.data
			const code = res.code || res.status || 200
			const msg = errorCode[code] || res.msg || errorCode['default']
			if (code === 401) {
				reject('无效的会话，或者会话已过期，请重新登录。')
				uni.showModal({
					title: '提示',
					content: '无效的会话，或者会话已过期，请重新登录',
					cancelText: '取消',
					confirmText: '确定',
					confirmColor: '#90d3e8',
					success: function(res) {
						if (res.confirm) {
							uni.redirectTo({
								url: '/pages/authSetting/authSetting'
							})
						}
					}
				})
			} else if (code == 403) {
				reject('登陆失效，请重新登录')
				uni.showModal({
					title: '提示',
					content: '登陆失效，请重新登录',
					cancelText: '取消',
					confirmText: '确定',
					confirmColor: '#90d3e8',
					success: function(res) {
						if (res.confirm) {
							uni.redirectTo({
								url: '/pages/authSetting/authSetting'
							})
						}
					}
				})
			} else if (code == 500) {
				reject()
				toast(msg)
			}
			resolve(response.data)
		})
	})
}
export const uploadImagePromise = (url) => {
	return new Promise((resolve, reject) => {
		let a = uni.uploadFile({
			url: baseUrl + '/mini/common/upload', // 仅为示例，非真实的接口地址
			filePath: url,
			name: 'file',
			header: {
				Authorization: uni.getStorageSync('token'),
				'Fw-Agent': 'mini/1.0.0'
			},
			success: (res) => {
				console.log(res, "++++++++++")
				if (res.statusCode == 200 && res.data) {
					let data = JSON.parse(res.data)
					resolve(data?.url || '')
				} else {
					resolve('')
				}
			},
			fail(err) {
				resolve('')
			}
		});
	});
};
export default request